<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图书ID" prop="bookId">
        <el-input
          v-model="queryParams.bookId"
          placeholder="请输入图书ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借阅时间" prop="borrowTime">
        <el-date-picker clearable
                        v-model="queryParams.borrowTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择借阅时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="应还时间" prop="dueTime">
        <el-date-picker clearable
                        v-model="queryParams.dueTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择应还时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="涉及金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入涉及金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['creditlife:borrowRecord']"
        >免押金借阅</el-button>
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="borrowRecordList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="图书ID" align="center" prop="bookId" />
      <el-table-column label="借阅时间" align="center" prop="borrowTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.borrowTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应还时间" align="center" prop="dueTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dueTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还时间" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="涉及金额" align="center" prop="amount" />
      <el-table-column label="分数影响" align="center" prop="creditImpact" />
      <el-table-column label="借阅状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === '未归还'"
                     link type="primary" icon="el-icon-edit" @click="extendLendDays(scope.row)" v-hasPermi="['creditlife:borrowRecord']">续借</el-button>
          <el-button link v-if="scope.row.status === '未归还'"
                     type="primary" icon="el-icon-edit" @click="returnBook(scope.row)" v-hasPermi="['creditlife:borrowRecord']">还书</el-button>
          <el-button v-if="scope.row.status === '已逾期'&&scope.row.returnTime===null"
                     link type="primary" icon="el-icon-delete" @click="returnBook(scope.row)" v-hasPermi="['creditlife:borrowRecord']">补缴</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 续借天数输入对话框 -->
    <el-dialog
      :title="renewDialogTitle"
      :visible.sync="renewDialogOpen"
      width="400px"
      append-to-body
    >
      <el-form
        :model="renewForm"
        :rules="renewRules"
        ref="renewFormRef"
        label-width="120px"
      >
        <el-form-item
          label="续借天数"
          prop="extendDays"
          required
        >
          <el-input
            v-model.number="renewForm.extendDays"
            type="number"
            min="1"
            :max="maxRenewDays"
            placeholder="请输入续借天数"
            clearable
          />
          <div class="mt-2 text-warning text-sm">
            <i class="el-icon-info"></i> 最多可续借 {{ maxRenewDays }} 天
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renewDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="handleRenewConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 借阅图书对话框-->
    <el-dialog :title="title" :visible.sync="open" width="80%" :style="{ height: '700px', overflow: 'auto' }" append-to-body>
      <el-input
        v-model="bookSearchKey"
        placeholder="请输入图书名称搜索"
        clearable
        style="margin-bottom: 15px;"
        @keyup.enter.native="handleBookSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleBookSearch"></el-button>
        <el-button slot="append" icon="el-icon-refresh" @click="resetBookSearch"></el-button>
      </el-input>
      <el-table
        :data="currentPageData"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="bookId"
          label="图书ID"
          width="100"
        />
        <el-table-column
          prop="bookName"
          label="图书名字"
        />
        <el-table-column
          prop="bookValue"
          label="图书单价"
          width="120"
        />
        <el-table-column
          prop="maxBorrowDays"
          label="最大借阅时间"
          width="140"
        />
        <el-table-column
          prop="bookNum"
          label="图书可借阅数量"
          width="140"
        />
        <el-table-column
          prop="overdueFeeRate"
          label="超出借阅时间费率"
          width="160"
        />
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="handleBorrow(scope.row)"
            >
              借阅
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="5"
        layout="total, prev, pager, next"
        :total="bookTotal"
        style="margin-top: 20px; text-align: right;"
      />
    </el-dialog>

    <!-- 借阅图书对话框选择借阅时间 -->
    <el-dialog
      :title="borrowDialogTitle"
      :visible.sync="borrowDialogOpen"
      width="600px"
      append-to-body
    >
      <el-form :model="borrowForm" label-width="120px">
        <el-form-item label="借阅时长" prop="lendDays">
          <el-select
            v-model="selectedDays"
            placeholder="请选择借阅天数"
            clearable
          >
            <el-option
              v-for="day in availableDaysOptions"
              :key="day"
              :label="`${day}天`"
              :value="day"
            />
          </el-select>
          <div class="mt-2 text-warning text-sm">
            <i class="el-icon-warning"></i> 您的免费借阅时间取决于信用分及图书可借阅时间
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="borrowDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="handleBorrowConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBorrowRecord, getBorrowRecord, delBorrowRecord, addBorrowRecord, updateBorrowRecord, borrowBook, getBookInfoList, getBorrowBookDays, returnBorrowBook, renewBook } from "@/api/creditlife/borrowRecord"

export default {
  name: "BorrowRecord",
  data() {
    return {
      // 续借对话框相关
      renewDialogOpen: false,
      renewDialogTitle: "续借图书",
      maxRenewDays: 7,
      borrowDialogOpen: false,
      borrowDialogTitle: "填写借阅时间",
      currentRenewRecord: null,
      borrowRecordList: [],
      open: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      renewForm: {
        extendDays: 1
      },
      total: 0,
      title: "",
      bookSearchKey: '',
      borrowForm: {
        borrowTime: "",
        bookId: ""
      },
      currentPage: 1,
      currentPageData: [],
      availableDaysOptions: [],
      selectedDays: 1,
      userAvailDays: null,
      rawBookData: [],
      bookTotal: 0,
      filteredBookData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        bookId: null,
        borrowTime: null,
        dueTime: null,
        returnTime: null,
        isOverdue: null,
        amount: null,
        creditImpact: null,
        status: null
      },
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        bookId: [
          { required: true, message: "图书ID不能为空", trigger: "blur" }
        ],
        borrowTime: [
          { required: true, message: "借阅时间不能为空", trigger: "blur" }
        ],
        dueTime: [
          { required: true, message: "应还时间不能为空", trigger: "blur" }
        ],
        isOverdue: [
          { required: true, message: "是否预期不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "涉及金额不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "借阅状态不能为空", trigger: "change" }
        ]
      },
      renewRules: {
        extendDays: [
          { required: true, message: "请输入续借天数", trigger: "blur" },
          { type: "number", min: 1, message: "续借天数不能小于1", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value > this.maxRenewDays) {
                callback(new Error(`续借天数不能超过${this.maxRenewDays}天`));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getBookList()
    this.getCreditAvailDays()
    this.calculateCurrentPageData()
  },
  activated() {
    this.getList()
    this.getBookList()
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val
      this.calculateCurrentPageData()
    },
    handleBorrow(row) {
      console.log(this.userAvailDays)
      this.borrowForm.bookId = row.bookId
      const bookMaxDays = row.maxBorrowDays
      const userAvail = this.userAvailDays || 0
      const maxSelectDays = Math.min(bookMaxDays, userAvail)

      if (maxSelectDays >= 1) {
        this.availableDaysOptions = Array.from({length: maxSelectDays}, (_, i) => i + 1)
      } else {
        this.availableDaysOptions = []
        this.$message.warning("当前图书无法借阅（超出最大借阅限制或您的信用分过低）")
        return
      }

      this.selectedDays = 1
      this.borrowDialogOpen = true
    },
    handleBorrowConfirm() {
      const bookId = this.borrowForm.bookId
      const lendTime = this.selectedDays
      if (!bookId) {
        this.$message.error("图书ID异常，请重新选择图书")
        return
      }
      if (!lendTime || lendTime <= 0) {
        this.$message.error("请选择有效借阅时间")
        return
      }
      borrowBook(bookId, lendTime)
        .then(response => {
          if (response.code === 200) {
            this.$message.success("借书成功！")
            this.borrowDialogOpen = false
            this.getBookList()
            this.getList()
          } else {
            this.$message.error(response.msg || "借书失败，请重试")
          }
        })
    },
    calculateCurrentPageData() {
      const start = (this.currentPage - 1) * 5
      const end = start + 5
      this.currentPageData = this.filteredBookData.slice(start, end)
    },
    handleBookSearch() {
      this.currentPage = 1
      if (this.bookSearchKey.trim()) {
        this.filteredBookData = this.rawBookData.filter(book =>
          book.bookName.toLowerCase().includes(this.bookSearchKey.toLowerCase().trim())
        )
      } else {
        this.filteredBookData = [...this.rawBookData]
      }
      this.bookTotal = this.filteredBookData.length
      this.calculateCurrentPageData()
    },
    getList() {
      this.loading = true
      listBorrowRecord(this.queryParams).then(response => {
        this.borrowRecordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    async handleRenewConfirm() {
      const valid = await this.$refs.renewFormRef.validate().catch(() => false)
      if (!valid) {
        return
      }

      if (!this.currentRenewRecord) {
        this.$message.error("续借数据异常，请刷新页面重试")
        this.renewDialogOpen = false
        return
      }

      const renewData = {
        id: this.currentRenewRecord.id,
        bookId: this.currentRenewRecord.bookId,
        userId: this.currentRenewRecord.userId,
        borrowTime: this.currentRenewRecord.borrowTime,
        dueTime: this.currentRenewRecord.dueTime,
        status: this.currentRenewRecord.status
      }

      renewBook(renewData, this.renewForm.extendDays)
        .then(response => {
          if (response.code === 200) {
            this.$message.success("续借成功！")
            this.renewDialogOpen = false
            this.getList()
          } else {
            this.$message.error(response.msg || "续借失败，请重试")
          }
        })
    },
    getBookList() {
      getBookInfoList().then(response => {
        if (response.code === 200) {
          this.rawBookData = response.rows || []
          this.filteredBookData = [...this.rawBookData]
          this.bookTotal = this.rawBookData.length
          this.calculateCurrentPageData()
        } else {
          this.$message.error("获取图书列表失败：" + response.msg)
        }
      }).catch(error => {
        this.$message.error("请求图书数据出错：" + error.message)
      }).finally(() => {
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      if (this.hasUnpaidOverdueOrder()) {
        this.$message.warning("当前有尚未支付订单，请支付完成后再借书")
        return
      }
      this.reset()
      this.open = true
      this.title = "免押金借阅"
    },
    hasUnpaidOverdueOrder() {
      return this.borrowRecordList.some(record => {
        return record.status === '已逾期' && record.returnTime == null
      })
    },
    reset() {
      this.form = {
        id: null,
        userId: null,
        bookId: null,
        borrowTime: null,
        dueTime: null,
        returnTime: null,
        isOverdue: null,
        amount: null,
        creditImpact: null,
        status: null
      }
      this.$refs.borrowRecordRef && this.$refs.borrowRecordRef.resetFields()
    },
    getCreditAvailDays() {
      getBorrowBookDays().then(response => {
        if (response.code === 200) {
          this.userAvailDays = response.data
        } else {
          this.$message.error("获取可免费借用天数失败" + response.msg)
        }
      }).catch(error => {
        this.$message.error("获取可免费借用天数失败：" + error.message)
      })
    },
    returnBook(row) {
      const returnData = {
        id: row.id,
        bookId: row.bookId,
        userId: row.userId,
        borrowTime: row.borrowTime,
        dueTime: row.dueTime,
        isOverdue: row.isOverdue,
        amount: row.amount,
        creditImpact: row.creditImpact,
        status: row.status
      }
      returnBorrowBook(returnData).then(response => {
        if (response.code === 200) {
          this.$message.success('归还成功')
          this.userAvailDays = response.data
          this.getList()
          this.getBookList()
        } else {
          this.$message.error('归还失败：' + response.msg)
        }
      }).catch(error => {
        this.$message.error('请求出错：' + error.message)
      })
    },
    extendLendDays(row) {
      this.currentRenewRecord = row
      this.renewForm.extendDays = 1
      if (this.$refs.renewFormRef) {
        this.$refs.renewFormRef.clearValidate()
      }
      this.renewDialogOpen = true
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.$refs.queryRef.resetFields()
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    resetBookSearch() {
      this.bookSearchKey = ''
      this.currentPage = 1
      this.filteredBookData = [...this.rawBookData]
      this.bookTotal = this.rawBookData.length
      this.calculateCurrentPageData()
    },
    handleExport() {
      this.download('creditlife/borrowRecord/export', {
        ...this.queryParams
      }, `borrowRecord_${new Date().getTime()}.xlsx`)
    },
    parseTime(time, format) {
      return time // placeholder - implement your actual time formatting
    }
  }
}
</script>
